﻿namespace Pap.Web.Modules.Administration.ViewModel
{
    using System;
    using System.Collections.Generic;
    using Microsoft.Practices.ServiceLocation;
    using Pap.Data;
    using Pap.Data.Abstraction.Utils;
    using Pap.Web.Utils;

    /// <summary>
    /// The Settings viewModel
    /// </summary>
    public class SettingsViewModel : IViewModel
    {
        /// <summary>
        /// The local repository object.
        /// </summary>
        private IAdministrationRepository _AdministrationRepository;

        /// <summary>
        /// Initializes a new instance of the <see cref="SettingsViewModel"/> class.
        /// </summary>
        /// <param name="repo">The repo.</param>
        public SettingsViewModel(IAdministrationRepository repo)
        {
            this._AdministrationRepository = repo;
        }

        /// <summary>
        /// Gets the settings.
        /// </summary>
        /// <param name="committeeGuid">The committee GUID.</param>
        /// <returns></returns>
        public IEnumerable<ISettingCategory> GetSettings(string committeeGuid)
        {
            return this._AdministrationRepository.GetSettingsForCommittee(new Guid(committeeGuid));
        }

        /// <summary>
        /// Saves the settings.
        /// </summary>
        /// <param name="commiteeGuid">The commitee GUID.</param>
        /// <param name="labels">The labels.</param>
        /// <param name="valuesToChange">The values to change.</param>
        public void SaveSettings(string commiteeGuid, string[] labels, string[] valuesToChange)
        {
            Guid comGuid = new Guid(commiteeGuid);
            string[] keys = new string[labels.Length];

            using (IUnitOfWork transaction = ServiceLocator.Current.GetInstance<IUnitOfWork>())
            {
                Dictionary<string, ISetting> labelToSettingMap = this._AdministrationRepository.GetLabelToSettingMapping(comGuid);

                for (int i = 0; i < labels.Length; i++)
                {
                    ISetting equivalentSetting = labelToSettingMap[labels[i]];
                    foreach (var validator in equivalentSetting.FieldValidator)
                    {
                        if (!validator.Validate(valuesToChange[i]))
                        {
                            throw new ArgumentException("Invalid value for " + equivalentSetting.Label, equivalentSetting.Label);
                        }
                    }

                    equivalentSetting.Value = valuesToChange[i];
                }

                transaction.Commit();
            }
        }

        /// <summary>
        /// Gets all committees.
        /// </summary>
        /// <returns></returns>
        public IEnumerable<ICommittee> GetAllCommittees()
        {
            return this._AdministrationRepository.GetAllCommittees();
        }
    }
}
